import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Plus, Edit, Trash2, Settings } from 'lucide-react';

const SkuEditor = ({ skus = [], onSkusChange }) => {
  const [skuAttributes, setSkuAttributes] = useState({
    颜色: ['黑色', '白色', '蓝色'],
    存储: ['128GB', '256GB', '512GB']
  });
  const [editingSku, setEditingSku] = useState(null);
  const [editForm, setEditForm] = useState({
    sku_code: '',
    price: '',
    stock: '',
    attributes: {}
  });

  // 生成SKU组合
  const generateSkuCombinations = () => {
    const attributeKeys = Object.keys(skuAttributes);
    const attributeValues = Object.values(skuAttributes);
    
    if (attributeKeys.length === 0) return [];
    
    const combinations = [];
    const generateCombos = (current, index) => {
      if (index === attributeKeys.length) {
        combinations.push(current);
        return;
      }
      
      const key = attributeKeys[index];
      const values = attributeValues[index];
      
      values.forEach(value => {
        generateCombos({ ...current, [key]: value }, index + 1);
      });
    };
    
    generateCombos({}, 0);
    return combinations;
  };

  // 添加SKU属性
  const handleAddAttribute = () => {
    const newKey = prompt('请输入属性名称（如：颜色、尺寸）');
    if (newKey && !skuAttributes[newKey]) {
      setSkuAttributes(prev => ({
        ...prev,
        [newKey]: []
      }));
    }
  };

  // 添加属性值
  const handleAddAttributeValue = (key) => {
    const newValue = prompt(`请输入 ${key} 的值`);
    if (newValue && !skuAttributes[key].includes(newValue)) {
      setSkuAttributes(prev => ({
        ...prev,
        [key]: [...prev[key], newValue]
      }));
    }
  };

  // 删除属性值
  const handleRemoveAttributeValue = (key, value) => {
    setSkuAttributes(prev => ({
      ...prev,
      [key]: prev[key].filter(v => v !== value)
    }));
  };

  // 删除属性
  const handleRemoveAttribute = (key) => {
    const newAttributes = { ...skuAttributes };
    delete newAttributes[key];
    setSkuAttributes(newAttributes);
  };

  // 开始编辑SKU
  const handleStartEditSku = (sku) => {
    setEditingSku(sku);
    setEditForm({
      sku_code: sku.sku_code || '',
      price: sku.price?.toString() || '',
      stock: sku.stock?.toString() || '',
      attributes: { ...sku.attributes }
    });
  };

  // 保存SKU编辑
  const handleSaveSku = () => {
    if (editForm.sku_code && editForm.price && editForm.stock) {
      const updatedSku = {
        ...editingSku,
        sku_code: editForm.sku_code,
        price: parseFloat(editForm.price),
        stock: parseInt(editForm.stock),
        attributes: editForm.attributes
      };
      
      const updatedSkus = editingSku
        ? skus.map(sku => sku.id === editingSku.id ? updatedSku : sku)
        : [...skus, { ...updatedSku, id: Date.now() }];
      
      onSkusChange && onSkusChange(updatedSkus);
      setEditingSku(null);
      setEditForm({ sku_code: '', price: '', stock: '', attributes: {} });
    }
  };

  // 删除SKU
  const handleDeleteSku = (skuId) => {
    const updatedSkus = skus.filter(sku => sku.id !== skuId);
    onSkusChange && onSkusChange(updatedSkus);
  };

  // 批量生成SKU
  const handleGenerateSkus = () => {
    const combinations = generateSkuCombinations();
    const basePrice = parseFloat(prompt('请输入基础价格') || '0');
    const baseStock = parseInt(prompt('请输入基础库存') || '0');
    
    const newSkus = combinations.map((attributes, index) => ({
      id: Date.now() + index,
      sku_code: `SKU${Date.now()}${index}`,
      price: basePrice,
      stock: baseStock,
      attributes
    }));
    
    onSkusChange && onSkusChange([...skus, ...newSkus]);
  };

  return (
    <div className="space-y-6">
      {/* SKU属性配置 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Settings className="size-5" />
            SKU属性配置
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {/* 属性列表 */}
            {Object.entries(skuAttributes).map(([key, values]) => (
              <div key={key} className="border rounded-lg p-4">
                <div className="flex items-center justify-between mb-2">
                  <Label className="font-medium">{key}</Label>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleAddAttributeValue(key)}
                    >
                      <Plus className="size-3 me-1" />
                      添加值
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleRemoveAttribute(key)}
                      className="text-destructive"
                    >
                      <Trash2 className="size-3" />
                    </Button>
                  </div>
                </div>
                <div className="flex flex-wrap gap-2">
                  {values.map((value, index) => (
                    <Badge key={index} variant="secondary" className="gap-1">
                      {value}
                      <button
                        onClick={() => handleRemoveAttributeValue(key, value)}
                        className="ml-1 hover:text-destructive"
                      >
                        ×
                      </button>
                    </Badge>
                  ))}
                </div>
              </div>
            ))}
            
            {/* 添加属性按钮 */}
            <Button variant="outline" onClick={handleAddAttribute}>
              <Plus className="size-4 me-2" />
              添加属性
            </Button>
            
            {/* 生成SKU按钮 */}
            {Object.keys(skuAttributes).length > 0 && (
              <Button onClick={handleGenerateSkus}>
                <Settings className="size-4 me-2" />
                批量生成SKU
              </Button>
            )}
          </div>
        </CardContent>
      </Card>

      {/* SKU列表 */}
      <Card>
        <CardHeader>
          <CardTitle>SKU列表</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {/* SKU表格 */}
            {skus.length > 0 && (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>SKU编码</TableHead>
                    <TableHead>价格</TableHead>
                    <TableHead>库存</TableHead>
                    <TableHead>属性</TableHead>
                    <TableHead className="w-24">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {skus.map((sku) => (
                    <TableRow key={sku.id}>
                      <TableCell className="font-medium">{sku.sku_code}</TableCell>
                      <TableCell>¥{sku.price}</TableCell>
                      <TableCell>{sku.stock}</TableCell>
                      <TableCell>
                        <div className="flex flex-wrap gap-1">
                          {Object.entries(sku.attributes).map(([key, value]) => (
                            <Badge key={key} variant="outline" className="text-xs">
                              {key}: {value}
                            </Badge>
                          ))}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-1">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleStartEditSku(sku)}
                          >
                            <Edit className="size-3" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleDeleteSku(sku.id)}
                            className="text-destructive hover:text-destructive"
                          >
                            <Trash2 className="size-3" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}

            {/* 编辑SKU表单 */}
            {editingSku && (
              <div className="border rounded-lg p-4 space-y-4">
                <h4 className="font-medium">编辑SKU</h4>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="space-y-2">
                    <Label>SKU编码</Label>
                    <Input
                      value={editForm.sku_code}
                      onChange={(e) => setEditForm(prev => ({ ...prev, sku_code: e.target.value }))}
                      placeholder="SKU编码"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>价格</Label>
                    <Input
                      type="number"
                      value={editForm.price}
                      onChange={(e) => setEditForm(prev => ({ ...prev, price: e.target.value }))}
                      placeholder="价格"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>库存</Label>
                    <Input
                      type="number"
                      value={editForm.stock}
                      onChange={(e) => setEditForm(prev => ({ ...prev, stock: e.target.value }))}
                      placeholder="库存"
                    />
                  </div>
                </div>
                
                {/* 属性编辑 */}
                <div className="space-y-2">
                  <Label>属性</Label>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {Object.entries(skuAttributes).map(([key, values]) => (
                      <div key={key} className="space-y-2">
                        <Label className="text-sm">{key}</Label>
                        <select
                          value={editForm.attributes[key] || ''}
                          onChange={(e) => setEditForm(prev => ({
                            ...prev,
                            attributes: { ...prev.attributes, [key]: e.target.value }
                          }))}
                          className="w-full px-3 py-2 border border-input rounded-md"
                        >
                          <option value="">请选择</option>
                          {values.map(value => (
                            <option key={value} value={value}>{value}</option>
                          ))}
                        </select>
                      </div>
                    ))}
                  </div>
                </div>
                
                <div className="flex gap-2">
                  <Button onClick={handleSaveSku} size="sm">
                    保存
                  </Button>
                  <Button
                    variant="outline"
                    onClick={() => setEditingSku(null)}
                    size="sm"
                  >
                    取消
                  </Button>
                </div>
              </div>
            )}

            {/* 空状态 */}
            {skus.length === 0 && !editingSku && (
              <div className="text-center py-8 text-muted-foreground">
                <p>暂无SKU信息</p>
                <p className="text-sm">请先配置SKU属性，然后生成SKU</p>
              </div>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default SkuEditor; 